<?php
// +-------------------------------------------------------------------------------
// | DingZone [ A Rapid Development Framework For Dingtalk ]
// +-------------------------------------------------------------------------------
// | UserController.php v1.0
// |
// | Copyright (c) 2014-2018 http://www.heimalanshi.com All rights reserved.
// | Author : Jie
// | Date : 2018-10-11
// +-------------------------------------------------------------------------------


namespace app\core\controller\enterprise\org;


use app\core\common\bean\BeanController;
use app\core\common\bean\BFC;
use app\core\controller\enterprise\EnterpriseBaseController;
use app\core\model\Enterprise;
use app\core\model\EnterpriseDept;
use app\core\model\EnterpriseUser;
use common\XXTEAEncryption;

class UserController extends EnterpriseBaseController {
    use BeanController;

    protected $deptid;

    public function __construct() {
        parent::__construct();

        $this->deptid = input("get.deptid");

        $this->_checkEnterpriseAdmin();
    }

    protected function _getBeanName() {
        return "enterprise_user";
    }

    protected function _getQueryConditions($fieldsConfig) {
        $conditions = $this->_getDefaultQueryConditions($fieldsConfig);

        if (!empty($this->deptid) && $this->deptid != EnterpriseDept::ROOT_DEPT_ID) {
            //如果是获取的指定部门的用户，则查找出包括子部门的人员
            $subDeptIds = EnterpriseDept::getSelfAndSubDeptIds($this->eid, $this->deptid);
            $conditions['id'] = ['in', function ($query) use ($subDeptIds) {
                $query->name('enterprise_dept_user')->where([
                    'enterprise_id' => $this->eid,
                    'deptid' => ['in', $subDeptIds]
                ])->field('userid');
            }];
        }

        if (isset($conditions['mobile'])) {
            $mobile = $conditions['mobile'];
            if (is_array($mobile)) {
                $mobile = $mobile[1];
                $mobile = str_replace("%", "", $mobile);
            }
            $conditions['mobile'] = EnterpriseUser::encodeMobile($mobile);
        }

        return $conditions;
    }

    protected function _getBeanFieldsConfig() {
        $configs = $this->_getDefaultBeanFieldsConfig();

        $configs['id'][BFC::KEY] = true;
        $configs['id'][BFC::HIDE] = true;
        $configs['username'][BFC::HIDE] = true;
        $configs['status'][BFC::HIDE] = true;
        $configs['mobile'][BFC::WIDTH] = 120;
        $configs['enterprise_id'][BFC::KEY] = true;
        $configs['password'][BFC::IGNORE] = true;
        $configs['avatar'][BFC::TYPE] = BFC::TYPE_IMAGE;
        $configs['openid'][BFC::HIDE] = true;
        $configs['dingid'][BFC::HIDE] = true;
        $configs['unionid'][BFC::HIDE] = true;
        $configs['gmt_last_login'][BFC::HIDE] = true;
        $configs['gmt_last_login'][BFC::TYPE] = BFC::TYPE_TIMESTAMP;
        $configs['last_login_ip'][BFC::HIDE] = true;
        $configs['is_admin'][BFC::TYPE] = BFC::TYPE_BOOL;
        $configs['is_admin'][BFC::HIDE] = true;
        $configs['is_senior'][BFC::TYPE] = BFC::TYPE_BOOL;
        $configs['is_senior'][BFC::HIDE] = true;
        $configs['jobnumber'][BFC::SORT] = true;
        $configs['id'][BFC::SEARCH] = [
            BFC::SEARCH_WIDTH => 4
        ];
        $configs['showname'][BFC::SEARCH] = [
            BFC::SEARCH_WIDTH => 4
        ];
        $configs['mobile'][BFC::SEARCH] = [
            BFC::SEARCH_WIDTH => 4
        ];
        $configs['jobnumber'][BFC::SEARCH] = [
            BFC::SEARCH_WIDTH => 4
        ];
        $configs['position'][BFC::SEARCH] = [
            BFC::SEARCH_WIDTH => 4
        ];

        $configs['depts'] = [
            BFC::TITLE => '所属部门',
            BFC::VIRTUAL => true,
            BFC::WIDTH => 200
        ];

        if (Enterprise::isPrivacyModeOn($this->eid)) {
            //如果开启了隐私模式，则隐藏手机号
            unset($configs['mobile']);
        }

        return $configs;
    }

    protected function _getCellMinWidth() {
        return 100;
    }

    protected function _rowPreProcess(&$row) {
        if (isset($row['mobile'])) {
            $row['mobile'] = XXTEAEncryption::decrypt($row['mobile'], DEFAULT_DECRYPT_KEY);
        }
        $row['status'] = EnterpriseUser::$STATUSES[$row['status']];
        return $row;
    }

    protected function _resultPreProcess(&$result) {
        if (!isset($result['data']) || empty($result['data'])) {
            return $result;
        }
        $deptMapping = EnterpriseDept::getDeptidTitleMapping($this->eid);
        foreach ($result['data'] as &$row) {
            $this->_rowPreProcess($row);

            $deptids = EnterpriseDept::getUserDeptIds($this->eid, $row['id']);
            if (empty($deptids)) {
                $row['depts'] = "";
            } else {
                $deptTitles = [];
                foreach ($deptids as $deptid) {
                    $deptTitle = fetch($deptMapping, $deptid);
                    if (!$deptTitle) {
                        continue;
                    }
                    $deptTitles[] = $deptTitle;
                }
                $row['depts'] = join(", ", $deptTitles);
            }
        }
        return $result;
    }

    protected function _getRowBtns() {
        $rowBtns = [];

        $rowBtns['edit'] = [
            BFC::ICON => 'edit',
            BFC::TIP => '编辑用户信息',
            BFC::ACTION => 'edit?userid=' . self::getParamPlaceholder("id"),
            BFC::DLG => [
                BFC::DLG_RELOAD => true,
            ]
        ];

        $rowBtns['del'] = [
            BFC::ICON => 'delete',
            BFC::CLAZZ => 'layui-bg-red',
            BFC::TIP => '删除用户',
            BFC::ACTION => 'del?userid=' . self::getParamPlaceholder("id"),
            BFC::AJAX => [
                BFC::AJAX_CONFIRM => '确认删除用户【' . self::getParamPlaceholder("showname") . '】？',
                BFC::AJAX_RELOAD => true
            ]
        ];

        return $rowBtns;
    }

    protected function _getGlobalBtns() {
        return [
            'add' => [
                BFC::ICON => 'add-1',
                BFC::TITLE => '新增员工',
                BFC::DLG => [
                    BFC::DLG_RELOAD => true
                ]
            ]
        ];
    }

    /**
     * 添加用户
     *
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add() {
        if (is_submit()) {
            $data = [];
            $data['showname'] = input("post.showname");
            $data['mobile'] = input("post.mobile");
            $deptid = input("post.deptid");
            $data['telephone'] = input("post.telephone");
            $data['email'] = input("post.email");
            $data['position'] = input("post.position");
            $data['sex'] = input("post.sex");
            $data['is_admin'] = input("post.isAdmin");
            $data['avatar'] = input("post.avatar");
            $data['political_status'] = input("post.political_status");
            $data['work_type'] = input("post.work_type");
            $gmtEnter = input("post.gmt_enter");
            $password = input("post.password");
            if (!empty($gmtEnter)) {
                $data['gmt_enter'] = strtotime($gmtEnter);
            }
            if (!empty($password)) {
                $data['password'] = EnterpriseUser::generatePassword($password);
            }

            $userid = EnterpriseUser::add($this->eid, $data, $deptid);

            if (!$userid) {
                $this->error("添加失败");
            } else {
                $this->success("添加成功", null, ['userid' => $userid]);
            }
        } else {
            $deptid = input("get.deptid");
            $deptTree = EnterpriseDept::getTree($this->eid);

            $this->assign("deptid", $deptid);
            $this->assign("deptTree", json_encode($deptTree));
            return view();
        }
    }

    /**
     * 编辑用户信息
     *
     * @return \think\response\View
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function edit() {
        if (is_submit()) {
            $userid = input("get.userid");

            $data = [];
            $data['showname'] = input("post.showname");
            $data['mobile'] = input("post.mobile");
            $data['telephone'] = input("post.telephone");
            $data['email'] = input("post.email");
            $data['position'] = input("post.position");
            $data['sex'] = input("post.sex");
            $data['is_admin'] = input("post.isAdmin");
            $data['avatar'] = input("post.avatar");
            $data['political_status'] = input("post.political_status");
            $data['work_type'] = input("post.work_type");
            $gmtEnter = input("post.gmt_enter");
            if (!empty($gmtEnter)) {
                $data['gmt_enter'] = strtotime($gmtEnter);
            }
            $deptids = input("post.deptids");
            $deptids = explode(",", $deptids);


            $ret = EnterpriseUser::updateById($this->eid, $userid, $data, $deptids);

            if (!$ret) {
                $this->error("更新失败");
            } else {
                $this->success("更新成功", null, ['userid' => $userid]);
            }
        } else {
            $userid = input("get.userid");
            $user = EnterpriseUser::getById($this->eid, $userid, true);

            if (empty($user)) {
                $this->error("未找到该用户");
            }

            $deptids = EnterpriseDept::getUserDeptIds($this->eid, $userid);
            $deptTree = EnterpriseDept::getTree($this->eid);

            $this->assign("deptTree", json_encode($deptTree));
            $this->assign("deptids", json_encode($deptids));
            $this->assign("editUser", $user);
            return view();
        }
    }
}